import java.util.Arrays;

/**
 * @Author: wanqian
 * @Date: 2021/2/3 17:24
 */
public class FibonacciSearch {
    //    public static int[] arr = {53, 3, 542, 748, 14, 214, 23, 77, 4, 5, 118, 45, 96, 1};
    public static int[] arr = {1, 2, 3, 4};

    public static void main(String[] args) {
        //需要对数组进行排序
        Arrays.sort(arr);
        System.out.println(String.format("排序后数组为： %s", Arrays.toString(arr)));
        int target = 4;
        int i = fibSearch(arr, target);

        if (i != -1) {
            System.out.println(String.format("找到目标arr[%d] = %d", i, target));
        } else {
            System.out.println("未找到目标");
        }
    }

    public static int[] fib() {
        int[] f = new int[20];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < f.length; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f;
    }

    public static int fibSearch(int[] arr, int key) {
        int low = 0;
        int high = arr.length - 1;
        int k = 0;
        int mid;
        int[] fib = fib();
        // 找到一个可以装载原数组
        // 长度为斐波那契数列的数
        while (arr.length > fib[k]) {
            k++;
        }
        //复制一个长度为fib[k]的临时数组
        int[] temp = Arrays.copyOf(arr, fib[k]);

        //新数组中空余的位置用最大值填充
        for (int i = high + 1; i < temp.length; i++) {
            temp[i] = arr[high];
        }

        while (low <= high) {
            mid = low + fib[k - 1] - 1;
            if (key < temp[mid]) {
                high = mid - 1;
                k--;
            } else if (key > temp[mid]) {
                low = mid + 1;
                k -= 2;
            } else {
                if (mid <= arr.length - 1) {
                    return mid;
                } else {
                    //因为当前查找的是扩充后的数组
                    //可能出现角标越界
                    return arr.length - 1;
                }
            }
        }
        return -1;
    }
}
